from urllib import request
import pytesseract
import os.path
from PIL import Image


# filename = "abc.png"
# img = Image.open("C:\\Test\\python\\" + filename)
# print(img)
#
# gray = img.convert('L')
# gray.save('C:\\Test\\python\\1-gray' + filename)
# bw = gray.point(lambda x: 0 if x < 1 else 255, '1')
# bw.save('C:\\Test\\python\\1-threshold' + filename)
# pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files (x86)\Tesseract-OCR\tesseract'
# word = pytesseract.image_to_string(img)
# print(word)


def print_word(path):
    img = Image.open(path)
    gray = img.convert('L')
    filename = os.path.split(path)[1]
    gray.save('C:\\Test\\python\\1-gray' + filename)
    bw = gray.point(lambda x: 0 if x < 1 else 255, '1')
    bw.save('C:\\Test\\python\\1-threshold' + filename)
    tessdata_dir_config = '--tessdata-dir "C:\\Program Files (x86)\\Tesseract-OCR\\tessdata"'
    pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files (x86)\Tesseract-OCR\tesseract'
    word = pytesseract.image_to_string(img, config=tessdata_dir_config, lang="chi_sim")
    print(word)
    print()

def linux_print_word(path):
    img = Image.open(path)
    gray = img.convert('L')
    filename = os.path.split(path)[1]
    gray.save('/home/liangchao/Pictures/1-gray' + filename)
    bw = gray.point(lambda x: 0 if x < 1 else 255, '1')
    bw.save('/home/liangchao/Pictures/1-threshold' + filename)
    tessdata_dir_config = '--tessdata-dir "/usr/share/tesseract-ocr/tessdata"'
    #pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files (x86)\Tesseract-OCR\tesseract'
    word = pytesseract.image_to_string(img, config=tessdata_dir_config)
    print(word)
    print()

if __name__ == '__main__':
    folder = "/home/liangchao/Pictures"
    files = os.listdir(folder)
    for file in files:
        linux_print_word(os.path.join(folder, file))
